<template>
  <el-card class="card-container">
    <div slot="header" class="card-header">
      <span class="card-title">{{ $route.meta.title }}</span>
      <div class="filter-item right-btns">
        <!-- <el-button class="opt-btn" type="primary" @click="edit">修改</el-button>
        <el-button class="opt-btn" type="primary" @click="del">删除</el-button> -->
      </div>
    </div>
    <el-row :gutter="20">
      <el-col :span="7">
        <el-card class="card-container">
          <div slot="header" class="card-header">
            <span class="card-title">组织架构</span>
            <span style="float: right;">
              <el-button
                v-if="$hasPermission('sys-organ-add') && ($store.getters.roleTypes.indexOf('1') >= 0 || $store.getters.roleTypes.indexOf('0') >= 0)"
                size="small"
                type="success"
                @click="add">
                <svg-icon icon-class="add"/> 新增
              </el-button>
              <el-button v-waves class="filter-item" type="default" size="small" icon="el-icon-refresh" @click="getTreeList">刷新</el-button>
              <!-- <el-button style="padding: 3px 0" type="text" @click="getTreeList">刷新</el-button> -->
            </span>
          </div>
          <el-form :model="filterOptions" :inline="true">
            <el-row>
              <el-col :span="14">
                <el-input v-model="filterOptions.filterText" placeholder="输入关键字进行过滤"/>
              </el-col>
              <el-col :span="10">
                <el-select v-model="filterOptions.organType">
                  <el-option :value="''" label="全部"/>
                  <el-option :value="'00'" label="协会"/>
                  <el-option :value="'01'" label="人身险"/>
                  <el-option :value="'02'" label="财产险"/>
                </el-select>
              </el-col>
            </el-row>
          </el-form>
          <div class="left-container">
            <el-tree
              v-loading="organLoading"
              ref="organTree"
              :data="deptData"
              :highlight-current="true"
              :default-expand-all="false"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              node-key="id"
              class="tree-container"
              @node-click="handleNodeClick">
              <span slot-scope="{ node, data }" class="tree-node">
                <span>{{ node.label }}</span>
                <span>
                  <span v-permission="'sys-organ-add-next'" class="opt-btn" @click.stop="add(node, data)" @ok="getTreeList"><svg-icon icon-class="add"/></span>
                  <span v-permission="'sys-organ-edit'" class="opt-btn" @click.stop="edit(node, data)" @ok="getTreeList"><svg-icon icon-class="pencil"/></span>
                  <span v-permission="'sys-organ-delete'" class="opt-btn" @click.stop="del(node, data)" @ok="getTreeList"><svg-icon icon-class="minus"/></span>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <el-col :span="17">
        <el-card class="card-container" style="margin-bottom: 20px;">
          <div slot="header" class="card-header">
            <span class="card-title">单位详情</span>
            <div v-show="deptDetail && deptDetail.id" class="card-opt-btn-list">
              <el-button v-permission="'sys-organ-add-contact'" class="opt-btn" type="success" size="small" plain @click="addContact">新增联系人</el-button>
            </div>
          </div>
          <el-form label-width="100px">
            <el-form-item label="名称：">
              <span>{{ deptDetail.name || '暂未设置' }}</span>
            </el-form-item>
            <el-form-item label="别名：">
              <span>{{ deptDetail.aliasName || '暂未设置' }}</span>
            </el-form-item>
            <el-form-item label="代码：">
              <span>{{ deptDetail.code || '暂未设置' }}</span>
            </el-form-item>
            <el-form-item label="联系人：" label-position="top">
              <!-- <el-tag v-for="tag in contactList" :key="tag.id" :closable="true" @close="delContact(tag)">
                {{tag.name}}（{{tag.phoneNo}}）
              </el-tag> -->
              <span v-for="tag in contactList" :key="tag.id" class="contact-tag" >
                <span class="tag-text">{{ tag.name }}（{{ tag.phoneNo }}）</span>
                <span class="tag-btn-list">
                  <span v-permission="'sys-organ-edit-contact'" @click="editContact(tag)"><svg-icon icon-class="pencil" class="tag-btn"/></span>
                  <span v-permission="'sys-organ-delete-contact'" @click="delContact(tag)"><svg-icon icon-class="remove" class="tag-btn"/></span>
                </span>
              </span>
              <span v-show="!contactList || !contactList[0]">暂未设置</span>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="card-container">
          <user-card ref="userManager" :options="userOptions" title="单位人员"/>
        </el-card>
      </el-col>
    </el-row>
    <add-edit-dialog ref="editDialog" :loading="isEditSubmitting" @ok="handleOk"/>
    <contact-dialog ref="contactDialog" :loading="isContactEditSubmitting" @ok="handleContactOk"/>
  </el-card>
</template>

<script>

// import pageMixin from '@/views/mixin/page'
import organApi from '@/api/systemManage/organ'
// import userApi from '@/api/user'

import addEditDialog from './add-edit'
import contactDialog from './contact'
import userCard from '../user'

import DelBoxMixin from '@/mixins/delBox'

export default {

  components: {
    addEditDialog,
    contactDialog,
    userCard
  },

  mixins: [DelBoxMixin],

  data() {
    return {
      deptData: [],
      selectedNode: null,

      deptDetail: {},
      tableData: [],

      userQueryParams: {
        organId: 'default'
      },

      contactList: [],
      currentContact: {},

      isEditSubmitting: false,
      isContactEditSubmitting: false,
      userOptions: {},
      filterOptions: {
        filterText: '',
        organType: ''
      },
      organLoading: false
    }
  },

  computed: {
    'userAddParams': function() {
      return {
        organId: this.deptDetail.id
      }
    }
  },

  watch: {
    filterOptions: {
      handler(val, oldValue) {
        this.$refs.organTree.filter(val)
      },
      deep: true
    }
  },

  mounted() {
    this.refresh()
  },

  methods: {

    refresh() {
      this.getTreeList()
    },

    getTreeList() {
      this.organLoading = true
      organApi.getTreeList().then(resp => {
        this.deptData = resp.data
        this.organLoading = false
      }).catch(resp => {
        this.$message.error(resp.message)
        this.organLoading = false
      })
    },

    handleNodeClick(data, node, comp) {
      this.userOptions.organId = data.id
      organApi.getById({
        id: data.id
      }).then(resp => {
        this.deptDetail = resp.data || {}
        this.getContactList()
        if (this.$refs.userManager) {
          this.userQueryParams.organId = this.deptDetail.id
          this.$refs.userManager.getList()
        }
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    },

    add(node, data) {
      this.selectedNode = node
      // this.isEdit = false
      // this.dialogVisible = true
      // this.dialogConfig.parentData = node.data
      this.$refs.editDialog.show(null, data)
    },

    edit(node, data) {
      // this.isEdit = true
      // this.dialogVisible = true
      // organApi.getById({
      //   id: data.id
      // }).then(resp => {
      //   this.dialogConfig.initData = resp.data
      // }).catch(resp => {
      //   this.$message.error(resp.message)
      // })
      let pdata = null
      if (data.parentId) {
        pdata = (this.$refs.organTree.getNode(data.parentId) || {}).data
      }
      this.$refs.editDialog.show(data, pdata)
    },

    del(node, data) {
      this.$$delBox().then(resp => {
        organApi.deleteById({
          id: data.id
        }).then(resp => {
          this.$refs['organTree'].remove(node)
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      }).catch(() => {})
    },

    handleOk(data, isEdit) {
      if (!isEdit && data) {
        this.processAdd(data)
      } else if (isEdit && data) {
        this.processEdit(data)
      }
    },

    processAdd(data) {
      if (this.selectedNode && this.selectedNode.data) {
        data.parentId = this.selectedNode.data.id
      }
      this.isEditSubmitting = true
      organApi.add(data).then(resp => {
        this.$refs.editDialog.close()

        if (this.selectedNode && this.selectedNode.data && resp.data) {
          data.label = data.name
          data.data = resp.data
          data.id = resp.data.id
          data.children = []
          const datas = this.selectedNode.data.children || []
          datas.push(data)
          datas.sort((a, b) => {
            const rt = a.data.sortNo - b.data.sortNo
            if (rt === 0) {
              return a.name - b.name
            }

            return rt
          })
          this.selectedNode.data.children = datas
        } else {
          this.refresh()
        }

        this.$message.success(resp.message)
        this.isEditSubmitting = false
      }).catch(resp => {
        this.isEditSubmitting = false
        this.$message.error(resp.message)
      })
    },

    processEdit(data) {
      this.isEditSubmitting = true
      organApi.edit(data).then(resp => {
        this.$refs.editDialog.close()

        if (this.deptDetail.id) {
          this.deptDetail = JSON.parse(JSON.stringify(data))
        }

        if (this.selectedNode && this.selectedNode.data && resp.data) {
          data.label = data.name
          data.data = resp.data
          data.children = this.selectedNode.data.children
          this.selectedNode.data = data
        } else {
          this.refresh()
        }
        this.$message.success(resp.message)
        this.isEditSubmitting = false
      }).catch(resp => {
        this.$message.error(resp.message)
        this.isEditSubmitting = false
      })
    },

    filterNode(opts, data) {
      if (!opts.filterText) {
        return opts.organType ? data.data.typeCode === opts.organType : true
      }

      const isOk = data.label.indexOf(opts.filterText) !== -1 || (data.data && data.data.code === opts.filterText)
      return isOk && (opts.organType ? data.data.typeCode === opts.organType : true)
    },

    // //////////////////////////////////////////////////
    addContact() {
      // this.isContactEdit = false
      // this.contactDialogVisible = true
      // this.contactDialogConfig.initData = null
      this.$refs.contactDialog.show()
    },

    editContact(item) {
      // console.log(item)
      // this.isContactEdit = true
      // this.contactDialogVisible = true
      // this.currentContact = item
      // this.contactDialogConfig.initData = this.currentContact
      this.$refs.contactDialog.show(JSON.parse(JSON.stringify(item)))
    },

    delContact(item) {
      this.$$delBox().then(resp => {
        organApi.deleteContactById({
          id: item.id
        }).then(resp => {
          const index = this.contactList.indexOf(item)
          this.contactList.splice(index, 1)
          this.$message.success(resp.message)
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      }).catch(() => {})
    },

    handleContactOk(data, isEdit) {
      // data = data.contactList[0]
      this.isContactEditSubmitting = true
      if (!isEdit) {
        data.organId = this.deptDetail.id
        organApi.addContact(data).then(resp => {
          this.getContactList()
          this.isContactEditSubmitting = false
          this.$refs.contactDialog.close()
          this.$message.success(resp.message)
        }).catch(resp => {
          this.isContactEditSubmitting = false
          this.$message.error(resp.message)
        })
      } else {
        organApi.editContact(data).then((resp) => {
          // this.contactDialogVisible = false
          // this.currentContact = data
          this.isContactEditSubmitting = false
          this.$refs.contactDialog.close()
          const index = this.contactList.findIndex(t => t.id === data.id)
          this.$set(this.contactList, index, data)
          this.$message.success(resp.message)
        }).catch(resp => {
          this.isContactEditSubmitting = false
          this.$message.error(resp.message)
        })
      }
    },

    getContactList() {
      this.currentContact = null
      organApi.getContactList({
        organId: this.deptDetail.id
      }).then(resp => {
        this.contactList = resp.data || []
      }).catch(resp => {
        this.$message.error(resp.message)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-title {
  padding: 15px 20px;
  border: none;
  border-radius: 5px;
  box-sizing: border-box;
}

.contact-tag {
  display: inline-block;
  height: 32px;
  line-height: 30px;
  font-size: 12px;
  padding: 0 20px;
  padding-right: 5px;
  border-radius: 4px;
  box-sizing: border-box;
  border: 1px solid rgba(64, 158, 255, 0.2);
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  margin: 0 5px;

  .tag-text {
    display: inline-block;
  }

  .tag-btn-list {
    $size: 14px;
    display: inline-block;
    line-height: $size;
    .tag-btn {
      display: inline-block;
      cursor: pointer;
      font-size: 12px;
      width: $size;
      height: $size;
      text-align: center;
      color: #409eff;
      padding: 2px;
      border-radius: 50%;

      &:hover {
        color: white;
        background: #409eff;
      }
    }
  }
}

.left-container {
  padding: 10px 5px;
  height: 500px;
  overflow-y: auto;
}
</style>
